package com.pi.pro.xcmg.am.was.web.cust.controller;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.annotation.JsonView;
import com.pi.common.CodesConstants;
import com.pi.common.utils.StringUtils;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.service.ICrudService;
import com.pi.framework.core.util.DateUtils;
import com.pi.framework.core.util.csv.CsvExporter;
import com.pi.framework.web.util.CsvView;
import com.pi.pro.xcmg.am.common.vo.report.StorageAgeListReportDto;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.dto.act.InventorySummaryReportDto;
import com.pi.wms.entity.TwaInventoryDetails;
import com.pi.wms.service.InventoryDetailsService;
import com.pi.wms.service.KanbanReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;


@Controller
@RequestMapping("/report/storageagereport")
public class StorageAgeReportController extends BaseCrudController<TwaInventoryDetails, Long> {

	@Value("${spring.datasource.database}")
	private String databasetype = CodesConstants.DATABASE_ORACLE;
	
	@Autowired
	@Qualifier("WMSINVDETAILSSERVICE")
	private InventoryDetailsService service;

	@Autowired
	private KanbanReportService reportService;

	@Override
	protected ICrudService<TwaInventoryDetails, Long> getCrudService() {
		return service;
	}

	@Override
	protected String getPrefix() {
		return "storageage_report";
	}

	@Override
	protected TwaInventoryDetails newModel(HttpServletRequest request) {
        TwaInventoryDetails stock = new TwaInventoryDetails();
		return stock;
	}

	@Override
	@GetMapping(value = { "" })
	public String list(Model model, @PathVariable Map<?, ?> params, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		setParams(request, params);
		model.addAttribute("params", params);
		return view("storageage_report");
	}

	@GetMapping("export")
	@ResponseBody
	public String export(Model model, Map<?, ?> params, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		return super.list(model, params, request, redirectAttributes);
	}

	@SuppressWarnings("deprecation")
	@ResponseBody
	@JsonView(value = { DataTablesOutput.View.class })
	@GetMapping(value = "storageageDatatable")
	public DataTablesOutput<StorageAgeListReportDto> storageageDatatable(@Valid DataTablesInput input,
                                                                                 @RequestParam Map<String, String> q) {
		Map<String, Object> query = new HashMap<>();
		query.put("clientId", StringUtils.isEmpty(q.get("clientId")) ? null : Long.parseLong(q.get("clientId")));
		query.put("divisionId", StringUtils.isEmpty(q.get("divisionId")) ? null : Long.parseLong(q.get("divisionId")));
		query.put("material", StringUtils.isEmpty(q.get("material")) ? null : String.valueOf(q.get("material")));

		Pageable pageable = new PageRequest((input.getStart() / input.getLength()), input.getLength());
		Page<StorageAgeListReportDto> dtos = this.reportService.queryStorageAgeListData(query, pageable, this.databasetype);

        DataTablesOutput<StorageAgeListReportDto> datatable = new DataTablesOutput();
        datatable.setDraw(input.getDraw().intValue());
        datatable.setData(dtos.getContent());
        datatable.setRecordsTotal(dtos.getTotalElements());
        datatable.setRecordsFiltered(dtos.getTotalElements());

		return datatable;
	}
	
	@PostMapping(value = { "/export" })
	public ModelAndView export(@RequestParam Map<String, Object> query, DataTablesInput input) {
		query.put("type", WmsConstants.TRANS_TYPE_SHIP);
		String inputParams = "";
		if (query.get("input")!=null){
			inputParams=query.get("input").toString();
		}
		if (StringUtils.isNotEmpty(inputParams)) {
			input = JSONArray.parseObject(inputParams, DataTablesInput.class);
		}
		input.setLength(-1);
		String ymd = DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HHMMSS);
		final DataTablesInput ins = input;

        CsvExporter<InventorySummaryReportDto> exporter = new CsvExporter<InventorySummaryReportDto>() {
            @Override
            public String[] header() {
                return "物料编码,物料名称,合计(笔),合计(箱),合计(托),合计(件)"
                        .split(",");
            }

            @Override
            public Collection<InventorySummaryReportDto> nextList(int pageSize, int page) {
                ins.setLength(pageSize);
                ins.setStart(page * pageSize);
        		Pageable pageable = PageRequest.of(page, pageSize);
                Page<InventorySummaryReportDto> out = service.summaryMaterialTotalData(query,pageable,StorageAgeReportController.this.databasetype);
                return out == null ? null : out.getContent();
            }

            @Override
            public Collection<String> toText(InventorySummaryReportDto d) {
                List<String> item = new ArrayList<String>();
                item.add(d.getMaterialcode() != null ? d.getMaterialcode() : "");
                item.add(d.getMaterialname() != null ? d.getMaterialname() : "");
                item.add(d.getSummtranscount() != null ? String.valueOf(d.getSummtranscount()) : "0");
                item.add(d.getSummtracecount() != null ? String.valueOf(d.getSummtracecount()) : "0");
                item.add(d.getSummcontaincount() != null ? String.valueOf(d.getSummcontaincount()) : "0");
                item.add(d.getSummquantity() != null ? String.valueOf(d.getSummquantity()) : "0.0");
                return item;
            }

        };
        return new ModelAndView(new CsvView(exporter, "storageage_" + ymd));
	}
}
